import axios from 'axios';

import Config from '../../config';
import getAPIHeader from '../get-api-headers';

export interface TokensResponse {
    abi: any;
    tokens: Token[];
}

export interface Token {
    networks: Network[];
    token: string;
    icon: string;
}

export interface TokenPrice {
    symbol: string;
    name: string;
    price: number; 
    icon: string;
}

export interface Network {
    id: string;
    name: string;
    icon: string;
    address: string;
}

export interface NetworkIsUp {
    up: boolean;
}

export default class TokenManager {
    static Endpoint = {
        performance: '/token/performance',
        token: '/multi-chain-payment/tokens',
        networkUp: '/multi-chain-payment/is-network-up',
        currencies: '/fiat/currencies'
    };

    static getCurrencies = async (): Promise<Array<string>> => {
        try {
            const call = await axios.get(`${Config.getAPI()}${TokenManager.Endpoint.currencies}`, {
                headers: await getAPIHeader()
            });

            if (call.data && call.data.fiat_currencies) {
                return call.data.fiat_currencies;
            }
        } catch (exception) {
            console.log(exception);
            return ['USD'];
        }

        return null;
    };

    static getPerformace = async () : Promise<Array<TokenPrice>> => {
        try {
            const call = await axios.get(Config.getAPI() + TokenManager.Endpoint.performance, {
                headers: await getAPIHeader()
            });
            
            if(call.data && call.data.tokens) {
                const tokens = new Array<TokenPrice>();
                for(let i = 0; i < call.data.tokens.length; i++) {
                    tokens.push({
                        symbol: call.data.tokens[i]['symbol'],
                        name: call.data.tokens[i]['name'],
                        price: call.data.tokens[i]['price'],
                        icon: call.data.tokens[i]['icon']
                    })
                }

                return tokens;
            }
        } catch (exception) {
            console.log(exception);
        }

        return null;
    }

    static getTokens = async (): Promise<TokensResponse> => {
        try {
            const call = await axios.get(Config.getAPI() + TokenManager.Endpoint.token, {
                headers: await getAPIHeader()
            });

            return call.data;
        } catch (exception) {
            console.log(exception);
            throw exception;
        }
    };

    static checkNetWorkUp = async (network: string): Promise<NetworkIsUp> => {
        try {
            const call = await axios.get(
                `${Config.getAPI()}${TokenManager.Endpoint.networkUp}?network=${network}`,
                {
                    headers: await getAPIHeader()
                }
            );

            return call.data;
        } catch (exception) {
            throw exception;
        }
    };
}
